﻿using System;
using System.Windows.Forms;

namespace Picea.Modelo
{

    public partial class TextBoxMoney : System.Windows.Forms.TextBox
    {

        public TextBoxMoney()
            : base()
        {
            //InitializeComponent();  
            this.Text = "0,00";
            this.DecimalPlaces = 2;
            this.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
        }

        #region '***[Propriedades]*********************************************************************

        private int varDecimalPlaces;

        [System.ComponentModel.Description("Define o Nº de casas decimais exibido pelo objeto."),
        System.ComponentModel.Category("Validação")]
        public int DecimalPlaces
        {
            get
            {
                return this.varDecimalPlaces;
            }

            set
            {
                if ((value < 0 | value > 6))
                {
                    throw new ArgumentOutOfRangeException("NumeroDeCasasDecimais", "O Valor deve estar entre 0 e 6 ");
                }
                else
                {
                    this.varDecimalPlaces = value;
                    this.Text = this.FormataStrToDec("0", this.DecimalPlaces);
                }
            }
        }

        private bool varNegativeValue;

        [System.ComponentModel.Description("Permite ou não valores negativos."),
        System.ComponentModel.DefaultValue(false),
        System.ComponentModel.Category("Validação")]
        public bool NegativeValue
        {
            get
            {
                return this.varNegativeValue;
            }
            set
            {
                this.varNegativeValue = value;
            }
        }

        private bool nonNumberEntered = false;

        #endregion

        #region '***[Eventos]**************************************************************************

        [System.ComponentModel.DefaultValue("0,00")]
        public override string Text
        {
            get
            {
                return base.Text;
            }

            set
            {
                if ((value == null) | (string.IsNullOrEmpty(value)))
                {
                    base.Text = this.FormataStrToDec("0", this.DecimalPlaces);
                }
                else
                {
                    base.Text = value;
                }
            }
        }

        protected override void OnTextChanged(System.EventArgs e)
        {
            base.OnTextChanged(e);

            if ((!this.Text.Contains("-")))
            {
                this.ForeColor = System.Drawing.Color.Black;
            }
            else
            {
                this.ForeColor = System.Drawing.Color.Red;
            }
        }

        protected override void OnGotFocus(System.EventArgs e)
        {
            base.OnGotFocus(e);

            //base.SelectAll();   
            //this.SelectAll();   

            if (string.IsNullOrEmpty(this.Text))
            {
                this.Text = this.FormataStrToDec("0", this.DecimalPlaces);
            }

            if (!this.Text.Contains("-"))
            {
                this.Text = this.FormataStrToDec(this.Text, this.DecimalPlaces);
                this.SelectAll();
            }
            else
            {
                this.Text = "-" + this.FormataStrToDec(this.Text.Replace("-", ""), this.DecimalPlaces);
                this.SelectionStart = this.Text.IndexOf("-") + "-".Length;
                this.SelectionLength = this.Text.Length - this.SelectionStart;
            }
        }

        protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs e)
        {
            base.OnKeyDown(e);

            nonNumberEntered = false;

            if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
            {

                if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
                {

                    if (e.KeyCode != Keys.Back)
                    {

                        if (NegativeValue & (int)e.KeyData == 109)
                        {
                            this.Text = "-" + this.FormataStrToDec(this.Text, this.DecimalPlaces);
                            this.SelectionStart = this.Text.IndexOf("-") + "-".Length;
                            this.SelectionLength = this.Text.Length - this.SelectionStart;
                        }

                        if ((e.KeyCode == Keys.Decimal | e.KeyCode == Keys.Oemcomma) | ((int)e.KeyData == 194 | e.KeyCode == Keys.OemPeriod))
                        {
                            if (!string.IsNullOrEmpty(this.Text))
                            {
                                this.Text = this.FormataStrToDec(this.Text, this.DecimalPlaces);
                                this.SelectionStart = this.Text.Length - this.DecimalPlaces;
                                this.SelectionLength = this.DecimalPlaces;
                            }
                        }
                        nonNumberEntered = true;
                    }
                }
            }
        }

        protected override void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
        {
            base.OnKeyPress(e);
            if (nonNumberEntered)
                e.Handled = true;
        }

        protected override void OnValidating(System.ComponentModel.CancelEventArgs e)
        {
            base.OnValidating(e);

            try
            {
                if (string.IsNullOrEmpty(this.Text))
                {
                    this.Text = this.FormataStrToDec("0", this.DecimalPlaces);
                }
                else
                {
                    this.Text = this.FormataStrToDec(this.Text, this.DecimalPlaces);
                }
            }
            catch (InvalidCastException ex)
            {
                MessageBox.Show("Formato Inválido, Redigite\n" + ex.Message, "Erro...", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Text = this.FormataStrToDec("0", this.DecimalPlaces);
            }

        }

        protected override void OnEnter(EventArgs e)
        {
            base.OnEnter(e);
            this.SelectAll();
        }

        protected override void OnMouseClick(MouseEventArgs e)
        {
            base.OnMouseClick(e);
            this.SelectAll();
        }

        #endregion

        #region '***[Função]***************************************************************************

        private string FormataStrToDec(string valor, int decimais)
        {

            string Resultado = System.Text.RegularExpressions.Regex.Replace(valor, "[^0-9]", "");

            if (Resultado == "")
            {
                valor = this.FormataStrToDec("0", this.DecimalPlaces);
                ;
            }

            switch (decimais)
            {

                case 1:
                    Resultado = String.Format("{0:#,0.0}", decimal.Parse(valor));
                    break;

                case 2:
                    Resultado = String.Format("{0:#,0.00}", decimal.Parse(valor));
                    break;

                case 3:
                    Resultado = String.Format("{0:#,0.000}", decimal.Parse(valor));
                    break;

                case 4:
                    Resultado = String.Format("{0:#,0.0000}", decimal.Parse(valor));
                    break;

                case 5:
                    Resultado = String.Format("{0:#,0.00000}", decimal.Parse(valor));
                    break;

                case 6:
                    Resultado = String.Format("{0:#,0.000000}", decimal.Parse(valor));
                    break;

                default:
                    Resultado = String.Format("{0:#,0}", decimal.Parse(valor));
                    break;
            }

            

            return Resultado;
        }

        #endregion
    }

}